package db

import (
	"fmt"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var DB *gorm.DB

type Config struct {
	Host     string
	Port     string
	User     string
	Password string
	DBName   string
}

// User 定义用户表结构
type User struct {
	ID          uint      `gorm:"primarykey" json:"id"`
	PhoneNumber string    `gorm:"unique;not null" json:"phone_number"`
	TotalAmount float64   `json:"total_amount"`
	MonthlyFee  float64   `json:"monthly_fee"`
	TotalMonths int       `json:"total_months"`
	HasRenewal  bool      `json:"has_renewal"`
	OrderDate   time.Time `json:"order_date"`
}

// InitDB 初始化数据库连接
func InitDB(config Config) error {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		config.User,
		config.Password,
		config.Host,
		config.Port,
		config.DBName,
	)

	var err error
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		return fmt.Errorf("连接数据库失败: %v", err)
	}

	// 自动迁移数据库表结构
	err = DB.AutoMigrate(&User{})
	if err != nil {
		return fmt.Errorf("数据库迁移失败: %v", err)
	}

	return nil
}

// GetUserByPhone 根据电话号码查询用户信息
func GetUserByPhone(phoneNumber string) (*User, error) {
	var user User
	result := DB.Where("phone_number = ?", phoneNumber).First(&user)
	if result.Error != nil {
		return nil, result.Error
	}
	return &user, nil
}

// UpdateUserRenewalStatus 更新用户的续约状态
func UpdateUserRenewalStatus(userID uint, hasRenewal bool) error {
	result := DB.Model(&User{}).Where("id = ?", userID).Update("has_renewal", hasRenewal)
	if result.Error != nil {
		return fmt.Errorf("更新续约状态失败: %v", result.Error)
	}
	return nil
}
